<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace App\Model;
use App\Entity\PayLog;
use App\Base\BaseModel;
use App\Entity\UserLive;
use App\Model\LazyCommon\RulesModel;
use App\Model\LazyCommon\UserModel;
use App\Setting\PayLogSetting;

class PayLogModel extends BaseModel{

    /*
     * 列表基本设置【通用模块必须开发】
     */
    public function listSettingDefault()
    {
        $settings = new PayLogSetting($this->getDoctrine());
        return $settings->listConfig();
    }

    /*
     * 为后台获取所有文章分类【通用模块必须开发】
     */
    /**
     * @param array $params $param[textKey]=textKey , $param[conditions][table][field][eq|gt|lt...]=value , $param[orderBy][table][field]=DESC|ASC
     * @param int $offset
     * @param int $perPage
     * @return array
     */
    public function getAdminLists($params ,$offset = 0 , $perPage = 10)
    {
        $qb = $this->getQueryFromParam($params);
        $lists = $this->getAllResult($qb,$offset,$perPage);
        $total = $this->countAllResult($qb);

        return array(
            "total" => $total ? $total : 0,
            "data"  => $lists
        );
    }

    /**
     * @return \Doctrine\Common\Persistence\ObjectRepository|\Doctrine\ORM\EntityRepository
     */
    public function getRep()
    {
        $settings = new PayLogSetting($this->getDoctrine());
        return $this->em->getRepository($settings->bundleName.":".$settings->entityName);
    }

    /**
     * @return PayLog[]
     */
    public function getAll()
    {
        return $this->getRep()->findBy(array(),array("id"=>"DESC"));
    }

    /**
     * @param $id
     * @return null|object|PayLog
     */
    public function getById($id)
    {
        return $this->getRep()->find($id);
    }

    /**
     * @return array
     */
    public function getAllArray()
    {
        $data = $this->getAll();
        $re = [];
        foreach ($data as $one) {
            $re[] = $this->toArray($one);
        }
        return $re;
    }

    /**
     * @param $id
     * @return array
     */
    public function getByIdArray($id)
    {
        $en = $this->getById($id);
        return $en?$this->toArray($en):[];
    }


    /**
     * @param $key
     * @param $val
     * @return PayLog
     */
    public function getByKV($key,$val)
    {
        $qb = $this->createDql();
        $qb->select("A")->from("App:PayLog","A");
        $qb->where("A.$key = :val")->setParameter("val",$val);
        $query = $qb->getQuery();
        $data = $query->execute();
        if ($data) {
            return $data[0];
        }else{
            return [];
        }
    }
    /**
     * @param array $arr
     * @return PayLog
     */
    public function getByKVs($arr =[])
    {
        $qb = $this->createDql();
        $qb->select("A")->from("App:PayLog","A");
        $i = 0;
        foreach ($arr as $key=>$val) {
            if ($i == 0) {
                $qb->where("A.$key = $val");
            }else{
                $qb->andWhere("A.$key = $val");
            }
            $i++;
        }
        $query = $qb->getQuery();
        $data = $query->execute();
        if ($data) {
            return $data[0];
        }else{
            return [];
        }
    }

    /**
     * @param $key
     * @param $val
     * @return PayLog[]
     */
    public function getArrayByKV($key,$val)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("A.*")->from("PayLog","A");
        $qb->where("A.$key = $val")->orderBy("id","DESC");
        $data = $qb->execute()->fetchAll();
        return $data;
    }


    /**
     * @param $userId
     * @param $money
     * @param array $data
     * @param int $payType
     * @param int $flag
     * @param int $outId
     * @return PayLog
     */
    public function createOrder($userId,$money,$data = [],$payType = 0,$flag = 0,$outId = 0)
    {
        $order = new PayLog();
        $order->setAddtime(time())
            ->setPayType($payType)
            ->setStatus(0)
            ->setSn($this->createOrderSn($userId))
            //上面是默认值，下面是传入值
            ->setUserId($userId)
            ->setMoney(abs($money))
            ->setOrderInfo(serialize($data))
            ->setPayType($payType)
            ->setFlag($flag)
            ->setOutId($outId);
        $this->em->persist($order);$this->em->flush();
        return $order;
    }

    //todo 各个项目根据自己的情况自定义这部分内容，考虑拿出去放到其他地方
    public function dealWithCallBack($sn)
    {
        $payLog = $this->getByKV("sn",$sn);
        if ($payLog && $payLog->getStatus() < 200) {
            //订单存在才处理
            $payLog->setStatus(200)
                ->setPaytime(time());
            $this->em->persist($payLog);$this->em->flush();
            switch ($payLog->getFlag()) {
                case 1://直播报名
                    $userId = $payLog->getUserId();
                    $liveId = $payLog->getOutId();

                    $UserLive = new UserLive();
                    $UserLive->setUserId($userId)
                        ->setLiveId($liveId)
                        ->setAddtime(time())
                        ->setPayLogId($payLog->getId());
                    $this->em->persist($UserLive);$this->em->flush();

                    break;
                case 2:
                    $userId = $payLog->getUserId();
                    $index = $payLog->getOutId();
                    $RulesModel = new RulesModel($this->getDoctrine());
                    $rule = $RulesModel->getByK("CHARGE_CONFIG");
                    $conf = unserialize($rule->getV());
                    $chargeConf = $conf[$index];//id传数组的index
                    $month = $chargeConf["month"];
                    $UserModel = new UserModel($this->getDoctrine());
                    $user = $UserModel->getUserById($userId);
                    $curTerm = $user->getWechat();
                    if ($curTerm < time()) {
                        $curTerm = time();
                    }
                    $targetTerm = strtotime("+ $month month",$curTerm);
                    $user->setWechat($targetTerm);
                    $this->em->persist($user);$this->em->flush();
                    break;
            }
            return false;
        }else{
            return "订单不存在";
        }
    }
}